package joney.main.views.table;

import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;

import joney.main.utils.FormatDecimal;
import joney.model.Expense;

import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;

public class ExpenseLabelProvider extends LabelProvider
implements ITableLabelProvider{

	private ExpenseList elist;

	public double startingAmount = 0;
	
	public ExpenseLabelProvider(ExpenseList elist)
	{
		this.elist = elist;
		startingAmount = elist.getAccount().getStartingAmount();
	}
	
	// Set the table column property names
	public static final String DATE 		= "Date";
	public static final String NAME 		= "Name";
	public static final String TYPE 		= "Type";
	public static final String AMOUNT_DEPOSIT 	=  "Deposit";
	public static final String AMOUNT_WITHDRAWL = "Withdrawl";
	public static final String TOTAL_AMOUNT 	=  "Total";
	public static final String NOTE = "Note";
	
	// Set column names
	public static final String[] columnNames = new String[] { 
		DATE, NAME, TYPE,AMOUNT_DEPOSIT, AMOUNT_WITHDRAWL, TOTAL_AMOUNT, NOTE};
	
	
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	private double calRuningTotal(Expense e)
	{
		Vector<Expense> exp =  elist.getExpenses();
		int index = exp.indexOf(e);
		double val =0;
		
		if(index == -1){return Double.NaN;}
		
		//offset the amount
		val+=startingAmount;
		
		for(int i= 0 ; i <= index; i++)
		{
			val+=exp.get(i).getAmount();
		}
		
		return val;
	}
	
	public String getColumnText(Object element, int columnIndex) {
		String result ="";
		Expense e = (Expense) element;
		switch (columnIndex) {
			case 0 :
				result = DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(e.getDate())).toString();
				break;
			case 1 :
				result = e.getName();
				break;
			case 2 :
				result = e.getType();
				break;
			case 3 : //deposit
				result =e.getAmount()>= 0? String.valueOf(FormatDecimal.format(2, e.getAmount())):"";
				break;
				
			case 4 : //withdrawl
				result = e.getAmount()< 0? String.valueOf(FormatDecimal.format(2, e.getAmount())):"";
				break;
			
			case 5:
				result = String.valueOf(FormatDecimal.format(2,calRuningTotal((Expense)element)));
				break;
				
			case 6:
				result = e.getNote();
				break;
			default :
				break; 	
		}
		return result;
	}

}
